#!/bin/bash

# 设置变量
ENV_NAME="airflow_env"
PYTHON_VERSION="3.10"
ADMIN_USERNAME="arvin"
ADMIN_FIRSTNAME="chen"
ADMIN_LASTNAME="arvin"
ADMIN_EMAIL="451292510@qq.com"
ADMIN_PASSWORD="111111aa"  # 为安全起见，考虑从环境变量或更安全的方式获取

# 创建 Conda 环境
echo "Creating Conda environment with Python $PYTHON_VERSION..."
conda create --yes --name $ENV_NAME python=$PYTHON_VERSION

# 激活环境
echo "Activating the Conda environment..."
source $(conda info --base)/etc/profile.d/conda.sh
conda activate $ENV_NAME

# 确保 pip 已安装
echo "Installing pip..."
conda install --yes pip

# 获取当前 Python 版本
PYTHON_VERSION=$(python -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')

# 获取最新版本的约束文件 URL（假设你知道最新版本号可以通过某种方式获取）
LATEST_AIRFLOW_VERSION="2.7.2"  # 修改此行以动态获取版本号
CONSTRAINT_URL="https://raw.githubusercontent.com/apache/airflow/constraints-${LATEST_AIRFLOW_VERSION}/constraints-${PYTHON_VERSION}.txt"

# 安装最新的 Apache Airflow
echo "Installing the latest Apache Airflow..."
pip install "apache-airflow==${LATEST_AIRFLOW_VERSION}" --constraint "${CONSTRAINT_URL}"

# 初始化数据库
echo "Initializing the Airflow database..."
airflow db init

# 创建管理员用户
echo "Creating admin user..."
airflow users create \
    --username "$ADMIN_USERNAME" \
    --firstname "$ADMIN_FIRSTNAME" \
    --lastname "$ADMIN_LASTNAME" \
    --role Admin \
    --email "$ADMIN_EMAIL" \
    --password "$ADMIN_PASSWORD"

# 提示用户启动 Web 服务器和调度器
echo "Airflow 已成功安装。要启动 Airflow，请运行以下命令："
echo "1. 启动 Web 服务器: airflow webserver --port 8080"
echo "2. 启动调度器: airflow scheduler"

# 提示用户访问 Airflow UI
echo "在浏览器中访问 http://localhost:8080 以查看 Airflow UI"
